package com.own.business.system.menu.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.own.business.system.menu.business.service.SystemRolePermissionService;
import com.own.business.system.menu.business.service.SystemRoleService;
import com.own.business.system.menu.business.service.SystemUserRoleService;
import com.own.business.system.menu.entity.bo.SystemRoleBo;
import com.own.business.system.menu.entity.map.SystemRoleMapVo;
import com.own.business.system.menu.entity.map.SystemRolePermissionMapVo;
import com.own.business.system.menu.entity.po.SystemRole;
import com.own.business.system.menu.entity.query.SystemRoleQuery;
import com.own.business.system.menu.entity.vo.SystemRoleVo;
import com.own.business.system.menu.mapper.SystemRoleMapper;
import com.own.component.common.base.service.impl.AbstractBaseService;
import com.own.component.common.model.UpdateModel;
import com.own.component.store.core.util.PermissionCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * SystemRoleServiceImpl
 *
 * @author chenxueli
 * @date 2024-03-31 09:22:58
 */
@Slf4j
@Service
public class SystemRoleServiceImpl extends AbstractBaseService<
        SystemRole,
        SystemRoleBo,
        SystemRoleVo,
        SystemRoleMapVo,
        SystemRoleQuery,
        SystemRoleMapper
        > implements SystemRoleService {

    @Resource
    private SystemRoleMapper systemRoleMapper;

    @Resource
    private SystemUserRoleService systemUserRoleService;
    @Resource
    private SystemRolePermissionService systemRolePermissionService;

    @Resource
    private PermissionCacheUtil permissionCacheUtil;

    /**
     * 获取查询条件
     *
     * @param query 查询条件
     * @return 查询条件对象
     */
    @Override
    public LambdaQueryWrapper<SystemRole> lambdaQueryWrapper(SystemRoleQuery query) {
        return super.lambdaQueryWrapper(query)
                .eq(query.getIsDisable() != null, SystemRole::getIsDisable, query.getIsDisable())
                .like(StringUtils.isNotBlank(query.getName()), SystemRole::getName, query.getName())
                .eq(StringUtils.isNotBlank(query.getClientId()), SystemRole::getClientId, query.getClientId())
                .orderByDesc(SystemRole::getGmtCreate, SystemRole::getId);
    }

    /**
     * 添加信息
     *
     * @param bo 添加对象
     * @return 添加标识
     */
    @Override
    public UpdateModel<SystemRoleVo> add(SystemRoleBo bo) {
        var model = super.add(bo);
        systemRolePermissionService.save(model.getData().getId(), bo.getPermissions());
        return model;
    }

    /**
     * 修改信息
     *
     * @param pk 主键id
     * @param bo 修改对象
     * @return 修改标识
     */
    @Override
    public UpdateModel<SystemRoleVo> update(Long pk, SystemRoleBo bo) {
        // 修改主信息
        var model = super.update(pk, bo);
        // 新增权限数据
        systemRolePermissionService.save(pk, bo.getPermissions());
        return model;
    }

    /**
     * 验证po对象
     *
     * @return 验证后的po对象
     */
    @Override
    public Function<SystemRoleVo, SystemRoleVo> checkAfter() {
        return vo -> {
            // 更新完成之后设置权限的全局信息
            permissionCacheUtil.setGlobalTimestamp();
            return vo;
        };
    }

    /**
     * 删除数据之后
     *
     * @param pk 删除数据的主键id
     * @return 处理后的vo对象
     */
    @Override
    public Boolean afterDelete(Long pk) {
        var flag = super.afterDelete(pk);
        // 更新完成之后设置权限的全局信息
        permissionCacheUtil.setGlobalTimestamp();
        return flag;
    }

    /**
     * 根据用户id查询角色列表
     *
     * @param userId 用户id
     * @return 角色列表
     */
    @Override
    public List<SystemRole> listByUserId(Long userId) {
        var roleIdList = systemUserRoleService.listRoleIdListByUserId(userId);
        return listByIdList(roleIdList);
    }

    /**
     * 根据用户id查询角色列表
     *
     * @param userId 用户id
     * @param client 客户端
     * @return 角色列表
     */
    @Override
    public List<SystemRole> listByUserId(Long userId, String client) {
        var roleIdList = systemUserRoleService.listRoleIdListByUserId(userId);
        if (roleIdList.isEmpty()) {
            return new ArrayList<>();
        }
        var wrapper = lambdaQueryWrapper()
                .in(SystemRole::getId, roleIdList)
                .eq(SystemRole::getClientId, client);
        return listByWrapper(wrapper);
    }

    /**
     * 根据角色id禁用角色
     *
     * @param roleId  角色id
     * @param disable 禁用状态 0-启用 1-禁用
     */
    @Override
    public void updateDisableById(Long roleId, Integer disable) {
        var po = getPoById(roleId);
        po.setIsDisable(disable == null ? ((po.getIsDisable() + 1) % 2) : (disable % 2));
        systemRoleMapper.updateById(po);
        // 更新完成之后设置权限的全局信息
        permissionCacheUtil.setGlobalTimestamp();
    }

    /**
     * 根据id获取信息之后处理的信息
     *
     * @param vo vo对象
     * @return 处理的vo对象
     */
    @Override
    public SystemRoleVo afterGetById(SystemRoleVo vo) {
        super.afterGetById(vo);
        if (vo != null) {
            // 查询当前角色的所有权限信息
            var systemRolePermissionList = systemRolePermissionService.listByRoleId(vo.getId());
            vo.setPermissions(systemRolePermissionList.stream().map(SystemRolePermissionMapVo::new).toList());
        }
        return vo;
    }

    /**
     * 删除信息
     *
     * @param pk 主键id
     * @return 删除标识
     */
    @Override
    public UpdateModel<Boolean> delete(Long pk) {
        // 删除对应的角色权限信息
        systemRolePermissionService.deleteByRoleId(pk);
        // 删除对应的角色用户信息
        systemUserRoleService.deleteByRoleId(pk);
        return super.delete(pk);
    }

}
